<?php

namespace app\model;

use think\Model;

class Admin extends Model
{
	// 设置当前模型对应的数据表
	protected $name = 'admin';
	// 设置当前模型主键
	protected $pk = 'id';

	public function getInfoById(int $id, string $fields = 'id')
	{
		$data = self::where(['id' => $id])->field($fields)->find();
		return $data ? $data->toArray() : [];
	}

	public function getInfoByWhere(array $where, string $fields = 'id')
	{
		$data = self::where($where)->field($fields)->find();
		return $data ? $data->toArray() : [];
	}

	//新增/更新
	public function edit($params)
	{
		if (empty($params['id'])) {
			$data = self::create($params);
			return $data->id;
		}
		self::update($params);
		return $params['id'];
	}

	public function getDataByWhere(array $where = [], string $fields = 'id', $order = 'id desc')
	{
		$data = self::where($where)->field($fields)->order($order)->select();
		return $data ? $data->toArray() : [];
	}

	// 获取分页数据
	public function getPagingDataByWhere($where = [], $page = 1, $limit = 10, string $fields = 'id, name', $order = 'id desc')
	{
		$total = self::where($where)->count();
		if ($total == 0) {
			return [
				'total'      => 0,
				'total_page' => 0,
				'data'       => []
			];
		}
		$offset = ($page - 1) * $limit;
		$totalPage = ceil($total / $limit);
		$data = self::where($where)->field($fields)->order($order)->limit($offset, $limit)->select()->toArray();
		return [
			'total'      => $total,
			'total_page' => $totalPage,
			'data'       => $data
		];
	}

	//删除管理员
	public function deleteAdminManager($id)
	{
		$model = self::find($id);
		return $model->save([
								'is_delete'  => 2,
								'deleted_at' => time()
							]);
	}

	//获取总数
	public function getCounts()
	{
		$count = self::where(['is_delete' => 1])->count();
		return $count;
	}
}